/*
 * Copyright 2009 Lukasz Wozniak
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 *
 * http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package pl.sind.http.basic;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URI;

import pl.sind.http.AbstractHttpConnector;
import pl.sind.http.HttpMethods;
import pl.sind.http.HttpRequest;
import pl.sind.http.HttpRequestException;
import pl.sind.http.HttpResponse;
import pl.sind.http.auth.AuthenticationStrategy;
import pl.sind.io.IO;

/**
 * Simple HTTP conector based on HttpURLConnection.
 * 
 * @author Lukasz Wozniak
 * 
 */
public class SimpleJavaHttpConnector extends
		AbstractHttpConnector<HttpURLConnection> {

	public SimpleJavaHttpConnector(Proxy proxy) {
		super(proxy);
	}

	@Override
	protected HttpRequest<HttpURLConnection> createConnection(
			HttpMethods method, URI target) throws HttpRequestException {
		try {
			HttpURLConnection con;
			if (proxy != null) {
				con = (HttpURLConnection) getURL(target).openConnection(proxy);
			} else {
				con = (HttpURLConnection) getURL(target).openConnection(Proxy.NO_PROXY);
			}
			return new UrlHttpRequest(con);
		} catch (Exception e) {
			throw new HttpRequestException(e);
		}
	}

	@Override
	protected HttpResponse<HttpURLConnection> execute(
			HttpRequest<HttpURLConnection> con) throws HttpRequestException {
		HttpURLConnection unwrap = con.unwrap();
		try {
			InputStream in = con.getInputStream();
			boolean hasBody  = in.available()>0;
			if(hasBody){
				unwrap.setDoOutput(true);
			}
			unwrap.connect();
			if(hasBody){
				IO.pump(in, unwrap.getOutputStream());
			}
		} catch (IOException e) {
			throw new HttpRequestException(e);
		}
		return new UrlHttpResponse(unwrap);
	}

	public Class<HttpURLConnection> getTarget() {
		return HttpURLConnection.class;
	}

}
